import React from "react";
import ReactDOM from "react-dom";
import {Select, Tooltip} from "antd";
import BaseComponent from "../../../redare/components/BaseComponent";

import BaseAreaPresenter from "../../../.gen/presenter/BaseAreaPresenter";
import {saveStorage,getStorage} from "../../../common/StorageUtils";

export default class AreaSelect extends BaseComponent {

  // 是否使用浏览器缓存策略
  isBrowseCachePlan = true;
  // 浏览器缓存Key前缀
  browseCacheKeyPrefix = "areaList";
  // 地区数据
  areaData={
    provinceCode: null,
    province: null,
    cityCode: null,
    city: null,
    districtCode: null,
    district: null,
    areaStr:null
  };


  constructor(props) {
    super(props);
    this.baseAreaPresenter = new BaseAreaPresenter(this);

    if( this.props.isBrowseCachePlan == false ){
        this.isBrowseCachePlan = this.props.isBrowseCachePlan;
    }

    this.state = {
      provinceLoading: false,
      cityLoading: false,
      cityOpen: false,
      districtLoading: false,
      districtOpen:false,
      provinceData: [],
      cityData: [],
      districtData: [],
      provinceValue: null,
      cityValue: null,
      districtValue: null
    }
  }

  componentDidMount() {
    // 默认只加载省
    this._loadProvinceData('CN');
    this.addListenEvent();
  }


  resetFields() {
    this.setState({
      provinceValue: null,
      cityValue: null,
      districtValue: null
    })
  }

  /**
   * 组件对外获取数据的函数
   * @param separator 字符串地址分隔符号
   * @returns
   */
  getData(separator){
    if( !separator ){
      separator = '';
    }
    let data = {...this.areaData};

    let areaStr =  data.province;

    if( !data.province ){
      return null;
    }

    if(  data.city ){
      areaStr += separator + data.city;
      if( data.district ){
        areaStr += separator + data.district;
      }
    }

    data.areaStr = areaStr;

    return data;
  }

  // 对组件进行赋值
  setData(data){
    let areaData={
      provinceCode: data.provinceCode,
      province: data.province,
      cityCode: data.cityCode,
      city: data.city,
      districtCode: data.districtCode,
      district: data.district,
      areaStr: data.areaStr
    };


    this.areaData = areaData;

    if( data.provinceCode ){
      this._loadCityData(data.provinceCode, true);
    }
    if( data.cityCode ){
      this._loadDistrictData( data.cityCode, true);
    }

    this.setState({
      provinceValue: data.provinceCode,
      cityValue: data.cityCode,
      districtValue: data.districtCode
    });

  }


  // 默认使用浏览器缓存方式获取数据
  _loadData(parentCode, callbackFn){

    let continueLoadServerData = false;

    if( this.isBrowseCachePlan ){
      let data = getStorage(this.browseCacheKeyPrefix+"_"+parentCode);
      if( data == null){
        continueLoadServerData = true;
      }else{
        if( callbackFn && typeof callbackFn === 'function'){
            callbackFn(data);
        }
        this.closeLoadingIndicator();
      }
    }else {
      continueLoadServerData = true;
    }

    if( continueLoadServerData ){
      this.__loadData(parentCode, callbackFn);
    }

  }

  // 核心请求服务接口后加载数据
  __loadData(parentCode, callbackFn){
    this.baseAreaPresenter.findAreaListByParentCode(
      {parentCode},
      {},
      (s_r)=>{
        let data = s_r.data;
        if (this.isBrowseCachePlan) {
          saveStorage(this.browseCacheKeyPrefix+"_"+parentCode, data);
        }
        if( callbackFn && typeof callbackFn === 'function'){
          callbackFn(data);
        }
      },
      (f_r)=>{

      }
    );
  }

  // 加载省数据
  _loadProvinceData(parentCode){
    this.setState({provinceLoading: true});
    this._loadData(parentCode, (data)=>{

      this.setState({provinceData: data});
    });
  }

  // 加载市数据
  _loadCityData(parentCode, silently){
    this.setState({
      cityLoading: true,
      provinceValue: parentCode,
      cityValue: null,
    });
    this._loadData(parentCode, (data)=>{
      this.setState({cityData: data});
      if( !silently && data && data.length > 0 ){
        // 使市获取的焦点
        if( this.citySelect ){
          this.citySelect.focus();
        }
        this.setState({cityOpen: true});
      }
    });
  }

  // 加载区数据
  _loadDistrictData(parentCode, silently){
    this.setState({
      cityOpen: false,
      cityValue: parentCode,
      districtLoading: true,
      districtValue: null
    });
    this._loadData(parentCode, (data)=>{
      this.setState({districtData: data});
      if( !silently && data && data.length > 0 ){
        // 使区获取的焦点
        if( this.districtSelect ){
          this.districtSelect.focus();
        }
        this.setState({districtOpen: true});
      }
    });
  }


  getOption(data){
    let options = [];
    if( !data || data.length === 0){
      return options;
    }
    data.map((item)=>{
      options.push(
        <Select.Option key={item.areaCode} value={item.areaCode} data={item}>
          <Tooltip title={item.areaName}>{item.areaName}</Tooltip>
        </Select.Option>
      );
    });
    return  options;
  }


  // 组装下拉数据
  _selectData(option, type){
    let data = option.data;
    this.areaData[type+"Code"] = data.areaCode;
    this.areaData[type] = data.areaName;
  }

  render() {

    let state = this.state;

    let selectAttr = {
      showSearch:true,
      optionFilterProp:"children",
      getPopupContainer: triggerNode => triggerNode.parentElement,
      onBlur: ()=>{
        this.setState({districtOpen: false, cityOpen: false});
      },
      filterOption: (inputValue,option)=>{
        if( option.data["areaName"].indexOf(inputValue) > -1 ){
          return true;
        }
        return false;
      }
    };


    return (

      <div className={'flex-son-margin5'} ref={(o)=>{this.selectGroup = o}}>
        <Select
          {...selectAttr}
          loading={state.provinceLoading}
          placeholder={"省"}
          value={state.provinceValue}
          onSelect={(value,option)=>{
            this._selectData(option, 'province');
            this._loadCityData(value);
          }}
        >
          {this.getOption( state.provinceData )}
        </Select>
        <Select
          {...selectAttr}
          ref={(the)=>{this.citySelect = the}}
          loading={state.cityLoading}
          placeholder={"市"}
          value={state.cityValue}
          open={state.cityOpen}
          onSelect={(value,option)=>{
            this._selectData(option, 'city');
            this._loadDistrictData(value);
          }}
        >
          {this.getOption( state.cityData )}
        </Select>
        <Select
          {...selectAttr}
          ref={(the)=>{this.districtSelect = the}}
          placeholder={"区"}
          loading={state.districtLoading}
          value={state.districtValue}
          open={state.districtOpen}
          onSelect={(value,option)=>{
            this._selectData(option, 'district');
            this.setState({districtValue: value, districtOpen: false});
          }}
        >
          {this.getOption( state.districtData )}
        </Select>
      </div>


    );
  }


  closeLoadingIndicator(){
    this.setState({
      provinceLoading: false,
      cityLoading: false,
      districtLoading: false
    });
  }

  addListenEvent(){

    // 不使用焦点因为第二次焦点本身就存在了焦点，所以第二次将无法展开
    let citySelect = ReactDOM.findDOMNode(this.citySelect);
    let districtSelect = ReactDOM.findDOMNode(this.districtSelect);

    let cityInput = citySelect.querySelector(".ant-select-selector");
    let districtInput = districtSelect.querySelector(".ant-select-selector");
    cityInput.addEventListener("click",  ()=> {
      this.setState({cityOpen: true});
    });
    districtInput.addEventListener("click",  ()=> {
      this.setState({districtOpen: true});
    });

  }

}
